<?php //if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Messages extends CI_Controller {

	function __construct(){

		parent::__construct();
		if(!isset($_SESSION)): session_start(); endif;
//		session_start();
//		//(isset($_SESSION['is_logged_in']) && $_SESSION['is_logged_in'] && isset($_SESSION['email']))? '':redirect('home');
		$this->load->model('messages_model');
		$this->load->model('users_model');
		$this->load->model('recipients_model');

	}

	public function index(){
		(isset($_SESSION['is_logged_in']) && $_SESSION['is_logged_in'] && isset($_SESSION['email']))? '':redirect('home');
		redirect('profile');
	}

	public function type( $task='photos' ){
		(isset($_SESSION['is_logged_in']) && $_SESSION['is_logged_in'] && isset($_SESSION['email']))? '':redirect('home');
		switch($task){
			case 'photos':
				$title = 'Photos';
				//$png = 'notes';
				$type = 'photos';
				break;
			case 'videos':
				$title = 'Videos';
				$type = 'videos';
				break;
			case 'notes':
				$title = 'Notes';
				//$png = 'notes';
				$type = 'notes';
				break;
				break;
			case 'documents':
				$title = 'documents';
				//$png = 'notes';
				$type = 'documents';
				break;

			case 'journal':
				$title = 'journal';
				//$png = 'notes';
				$type = 'journal';
				break;

			case 'pdf':
				$title = 'pdf file';
				//$png = 'notes';
				$type = 'pdf';
				$pdf_file_id = $this->uri->segment(4, 0);
				$pdf_file_id =  ($pdf_file_id==0) ? exit('File not found ') : $pdf_file_id;

				//Pdf File Creator
				$this->load->helper("pdf_creator");

				$pdf = new pdf_creator();
				$pdf->AddPage();
				$pdf->SetFont('Arial','B',16);
				$pdf->Cell(40,10,"data is here  $pdf_file_id ");
				$pdf->Output();

				exit();
				break;
		}

		$messages = $this->messages_model->getMessages($type);
		foreach($messages as $k=> $message){
			if($message->type == 'photos' || $message->type == 'videos' ){
				$files = Myuser_helper::getFiles($message->messageid);
				$thumbsrc = base_url().'assets/images/useruploads/'. (isset($files[0]->path) ? $files[0]->path : 'noimage.jpg');
//				print_r($files[0]);
				$messages[$k]->thumb = $thumbsrc;
			}
		}
//		print_r($messages);
		$data['message'] = $messages;
		$data['title']= "Messages: ".$title;
		$data['main_content'] = 'profile/messages_view';
		$this->load->view('include/template', $data);

	}

	function add(){
		$data['title']= "Messages: ".'add';
		$data['main_content'] = 'profile/messages_add_view';
		$this->load->view('include/template', $data);
	}

	function createMessage(){
		$newid = $this->messages_model->addMessages();
		$totype = $this->input->post('totype');
		if($newid){
			 if($totype == 'specific'){
			 	$recipA = ($this->input->post('recipientid')) ? $this->input->post('recipientid') : null;
			 	if(!empty($recipA)){
			 		$data['messageid'] = $newid;
			 		foreach($recipA as $r){
				 		//save recipients
					 	$data['recipientid'] = $r;
						$this->db->insert('mlme_messages_recipients_x', $data);
			 		}
			 	}

			 }

		}

/*
		$id = urlencode($this->encryption_lib->encode($newid));
		$msgDetails = $this->messages_model->getMessage($newid);
		$msgtype = $msgDetails['type'];
		$pdf_url = base_url().'messages/type/pdf/'.$msgDetails['pdf_id'];
		$files = myuser_helper::getFiles($newid);
		$thumbsrc = base_url().'assets/images/useruploads/'. (isset($files[0]->path) ? $files[0]->path : 'noimage.jpg');
		$preview = '<td><img src="'.$thumbsrc.'" class="thumbpreview" /></td>';

		if($msgtype == 'notes' || $msgtype== 'journal' || $msgtype == 'documents' ){
			$preview = '';
		}

		$shtml = '';

		if($msgDetails['totype'] == 'specific'){
			$reciplist = Myuser_helper::getRecipients($newid);
			$shtml .= '
					<div id="msg-recip-mainwrap">
					<div>
					<div class="sent-dropdown" onclick="javascript:recipDropdown('.$newid.')">.</div>';

					if(!empty($reciplist)){
						$shtml .='<div id="msg-recipient-wrap-'.$newid.'" class="absolute-recip" onmouseout="javascript:toggleRecipWrap();">
									<ol class="recip-ol">';
						foreach(@$reciplist as $k=>$recip){
							$shtml .='<li><span class="recip-ol-name">'.ucfirst(@$recip->fname).' '.ucfirst(@$recip->mname).' '.ucfirst(@$recip->lname).'</span>
									<span class="recip-ol-email"> &lt;'.@$recip->email.'&gt;</span></li>';
						}
						$shtml .= '</ol>';
						$shtml .= '</div>';
					} else {
						$shtml .= '<div id="msg-recipient-wrap-'.$newid.'" class="absolute-recip">';
						$shtml .= '<span>No recipient for this message.</span>';
						$shtml .= '</div>';
					}
			$shtml .= '</div></div>';
		}


		$html = '';

		$html .='

				<tr class="mssg" id="mssg'.$newid.'">
					'.$preview.'
					<td>
						<a class="msg-subject" href="'.base_url().'messages/view/'.$msgDetails['type'].'/'.$id.'">
						<span>'.ucwords($msgDetails['subject']).'</span></a><br />
						<span class="msg-add-details">'.date('M d, Y',strtotime($msgDetails['date_added'])).' | Sent to '.getTotype($msgDetails['totype'])
						.$shtml.
						'</span>
					</td>
					<td>
						<a class="get-pdf-file" href="'.$pdf_url.'" title="Download code details">.</a><a href="#" class="msg-delete-btn" title="Delete this message" onclick="javascript:DeleteMessage(\''.$newid.'\');">.</a></td>
					</tr>';

		echo $html; exit;

		//return $this->db->insert_id();

	//	print_r($msgDetails->result());
*/
		return true;
	}

	function countMessages(){
		$query = $this->messages_model->countMessages($type);
		return $query;
	}

	function view( $type, $id ){
		(isset($_SESSION['is_logged_in']) && $_SESSION['is_logged_in'] && isset($_SESSION['email']))? '':redirect('home');
		if(!$id) return;
		$id = urldecode($this->encryption_lib->decode($id));
		$data['idd'] = $id;
		$data['row'] = $this->messages_model->getMessage($id);
		$data['type'] = $type;
		$data['title']= 'View Message';
		$data['main_content'] = 'profile/messages_show_view';
		$this->load->view('include/template', $data);
	}

	// used to upload the browsed files from uploadify

	function upload() {
		if (!empty($_FILES)) {
			$tempFile = $_FILES['Filedata']['tmp_name'];
			$targetPath = $_SERVER['DOCUMENT_ROOT'] . '/mlme/assets/images/useruploads'. $_REQUEST['folder'] . '/';

			//get the last messageid
			$q = $this->db->query("SELECT MAX(messageid) as id from mlme_messages");
			$r= $q->row();
			$id = $r->id;

			$fileparts = pathinfo($_FILES['Filedata']['name']);
			$newfilename = $id.'_'.md5($_SERVER['REMOTE_ADDR'].rand()).'.'.$fileparts['extension'];

			$targetFile =  str_replace('//','/',$targetPath) . $newfilename;
//			$targetFile =  str_replace('//','/',$targetPath) . $_FILES['Filedata']['name'];
			mkdir(str_replace('//','/',$targetPath), 0755, true);

			move_uploaded_file($tempFile,$targetFile);
			//echo str_replace($_SERVER['DOCUMENT_ROOT'],'',$targetFile);

			//save data
			$data['messageid'] = $id;
			$data['path'] = $_REQUEST['folder'].'/'.$newfilename;
			$this->db->insert('mlme_messages_files_x',$data);
		}
	}

	//used to move the captured photos from temporary folder to the right one

	function uploadCaptured(){
		//get the last messageid
		$q = $this->db->query("SELECT MAX(messageid) as id from mlme_messages");
		$r= $q->row();
		$id = $r->id;

		$msgtype = $_POST['msgtype'];
		$capturedA = $_POST['capturedA'];
		$targetPath = $_SERVER['DOCUMENT_ROOT'];

		$newPath = $targetPath . '/mlme/assets/images/useruploads/messages/'. $msgtype . '/';

		$imgsPathA = array();

		foreach( $capturedA as $urlPath ){
			$parsed = parse_url($urlPath);
			$tempPath = $targetPath.$parsed['path'];
			$filename = $newPath.basename($tempPath);
			rename($tempPath, $filename);

			//save data
			$data['messageid'] = $id;
			$data['path'] = '/messages/'. $msgtype.'/'.basename($tempPath);
			$this->db->insert('mlme_messages_files_x',$data);

		}
		echo true;
		exit;
	}

	//delete data
	function delete( $id=array() ){
		$this->load->model('messages_model','',TRUE);
		$result = false;
		if( $this->messages_model->deleteMessage( $id ) ){
			$result = true;
		}
		echo $result; exit;
	}



}// end of controller
